package com.sprite.framework.entity.mapper.reolver;

import java.util.List;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.sprite.framework.entity.mapper.MapperException;
import com.sprite.framework.entity.mapper.StatementMapper;
import com.sprite.framework.entity.mapper.reolver.node.MixedSqlNode;
import com.sprite.utils.UtilString;
import com.sprite.utils.UtilXml;

public final class StatementResolver {
	
	public static StatementMapper reolve(Element element, String namespace){
		String tag = element.getTagName();
		
		if(!"select".equals(tag) && !"insert".equals(tag) && !"update".equals(tag) && !"fragment".equals(tag)){
			throw new MapperException("unsupprot tag :"+ tag);
		}
		
		String statementId = namespace+"."+ element.getAttribute("id");
		if(UtilString.isBlank(statementId)){
			throw new MapperException("statement not has id");
		}
		
		SqlNode rootNode = null;
		List<Node> sqlNodes = UtilXml.childNodeList(element);
		
		if(sqlNodes.size() == 1){
			rootNode = Parser.parser(sqlNodes.get(0));
		}else{
			MixedSqlNode mixedSqlNode = new MixedSqlNode();
			for(Node el : sqlNodes){
				SqlNode node = Parser.parser(el);
				if(node != null){
					mixedSqlNode.append(node);
				}
			}
			
			rootNode = mixedSqlNode;
		}
		
		return new StatementMapper(rootNode, statementId, namespace);
	}
	
	
}
